package com.tuhao.www.filter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;


/**
 * springmvc安全过滤
 * 
 * 过滤安全连接，必须要登录：如果是pc用户，则返回到页面， 如果是微信用户，则返回401json，由客户端自行根据401码进行跳转
 * 
 *
 */
public class SecurityFilter extends HttpServlet implements Filter {

	protected final Log logger = LogFactory.getLog(this.getClass());

	private static final long serialVersionUID = -6871710000081143385L;

	private static final String CONTENT_TYPE = "text/html; charset=UTF-8";

	private FilterConfig filterConfig;

	// 需要过滤的页面地址字符串，多个用半角逗号分隔
	private String excludeUrl;

	// 需要过滤的页面地址数组，经过excludeUrl对,进行split得到
	private String[] excludeUrlArray;

	// session为空时页面跳转的地址
	private String sessionNullUrl;

	public SecurityFilter() {
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
		this.excludeUrl = filterConfig.getInitParameter("excludeUrl");
		if (excludeUrl != null) {
			excludeUrlArray = excludeUrl.split(",");
		}
		this.sessionNullUrl = filterConfig.getInitParameter("sessionNullUrl");
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) {
		try {
			HttpServletRequest httpRequest = (HttpServletRequest) request;
			HttpServletResponse httpResponse = (HttpServletResponse) response;

			//httpResponse.setContentType(CONTENT_TYPE);

			String currentUrl = httpRequest.getServletPath();
			// String refererUrl = httpRequest.getHeader("referer");
			/* 获取当前浏览器路径 */
			// logger.info("currentUrl url:"+currentUrl);

			boolean flag = false;

			if (excludeUrlArray != null && excludeUrlArray.length > 0) {
				for (String regex : excludeUrlArray) {
					if (this.matches(regex.trim(), currentUrl.trim())) {
						flag = true;
						break;
					}
				}
			}

			if (flag) {
				// 获取用户session
				/*User user = (User) httpRequest.getSession().getAttribute(Constant.SESSION_USER);
				if (null != user) {
					// logger.info("login name is "+user.getLoginName());
					filterChain.doFilter(httpRequest, httpResponse);
				} else {

					// 如果是pc用户，则返回到页面
					if (!(httpRequest.getHeader("accept").indexOf("application/json") > -1 || (httpRequest.getHeader("X-Requested-With") != null && httpRequest.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))) {
//						httpRequest.getRequestDispatcher(sessionNullUrl + "?timeout=1&redirectURL=" + currentUrl).forward(httpRequest, httpResponse);
						httpResponse.sendRedirect(sessionNullUrl + "?timeout=1&redirectURL=" + currentUrl);
					} else {
						// 如果是微信用户，则返回401json，由客户端自行根据401码进行跳转
						JsonResult json = new JsonResult();
						json.setFlag(0);
						json.setStatus(401);
						json.setMsg("请登录");
						JSONObject.toJSONString(json);
						StringUtils.renderJson(httpResponse, JSONObject.toJSONString(json));
					}*//*
				}*/

			} else {
				filterChain.doFilter(httpRequest, httpResponse);
			}

		} catch (Exception e) {
			filterConfig.getServletContext().log(e.toString());
			e.printStackTrace();
		}
	}

	public void destroy() {
	}

	/**
	 * 通过正则表达式匹配字符串
	 * 
	 * @param regex
	 *            String
	 * @param input
	 *            CharSequence
	 * @return boolean
	 */
	private boolean matches(String regex, CharSequence input) {
		if (regex == null || input == null) {
			return true;
		} else if (regex.equals(input)) {
			return true;
		} else if (regex.indexOf("*") > -1) {
			PathMatcher pathMatcher = new AntPathMatcher();
			return pathMatcher.match(regex, input.toString());
		} else {
			return false;
		}
	}

	public static void main(String[] arg) {
		String regex = "/m/account/**/*.htm";
		CharSequence input = "/m/account/info.htm";
		PathMatcher pathMatcher = new AntPathMatcher();
		System.out.println(pathMatcher.match(regex, input.toString()));

	}
}
